<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>饼状图</title>
</head>

<body>
  <canvas id="canvas" width="600" height="400"></canvas>
  <script>
    class PieChart {
      constructor(data) {
        this.data = data;
        this.oCanvas = document.getElementById("canvas")
        this.ctx = this.oCanvas.getContext("2d")
        this.setRatio()
        this.x0 = this.oCanvas.width / 2;
        this.y0 = this.oCanvas.height / 2;
        this.r = 200;
        this.init()
      }
      toAngle() {
        const count = this.data.reduce((a, b) => a.num + b.num)
        console.log(count)
        this.data = this.data.map(item => {
          return {
            ...item,
            angle: item.num / count * Math.PI * 2,
            color: this.randomColor()
          }
        })
      }
      randomColor() {
        return `rgba(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
      }
      drawPie() {
        let start = 0;
        // this.ctx
        this.data.forEach(item => {
          this.ctx.beginPath()
          this.ctx.moveTo(this.x0, this.y0)
          this.ctx.arc(this.x0, this.y0, this.r, start, start + item.angle, false)
          this.ctx.closePath()
          this.ctx.fillStyle = item.color;
          this.ctx.fill()//默认填充黑色

          start += item.angle
        });
        console.log(this.data)
      }
      init() {
        this.toAngle()
        this.drawPie()
      }
      setRatio() {
        // 通过屏幕分辨率和画布分辨率重新设置canvas宽高-达到适应屏幕分辨率的目的
        let d = window.devicePixelRatio || 1;
        let cd = this.ctx.backingStorePixelRatio || 1;
        let r = d / cd;
        let oldW = this.oCanvas.width;
        let oldH = this.oCanvas.height;
        this.oCanvas.width = r * oldW;
        this.oCanvas.height = r * oldH;
        this.oCanvas.style.width = oldW + 'px';
        this.oCanvas.style.height = oldH + 'px';
      }
    }
    let data = [
      {
        title: "a",
        num: 100
      },
      {
        title: "b",
        num: 100
      },
      {
        title: "c",
        num: 100
      },
    ]
    let pieChart = new PieChart(data);
  </script>
</body>

</html>